<template>
  <div>
    <el-card style="height: 80px">
      <el-form inline class="searchForm">
        <el-form-item label="角色名称:"
          ><el-input v-model="keyword" placeholder="角色名称关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="default"
            @click="searchRole"
            :disabled="!keyword"
            >搜索</el-button
          >
          <el-button
            type="default"
            size="default"
            @click="settingStore.refsh = !settingStore.refsh"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-button size="default" icon="Plus" type="primary" @click="addRole"
        >添加角色</el-button
      >
      <el-table
        border
        :data="roleList"
        style="margin-top: 10px"
        v-loading="tableLoading"
      >
        <el-table-column
          align="center"
          label="序号"
          type="index"
          width="60"
        ></el-table-column>
        <el-table-column align="center" label="ID" prop="id"></el-table-column>
        <el-table-column
          align="center"
          label="角色名称"
          prop="roleName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #="{ row }">
            <el-button
              size="small"
              icon="User"
              type="primary"
              @click="setPermission(row)"
              >分配权限</el-button
            >
            <el-button
              size="small"
              icon="Edit"
              type="warning"
              @click="updateRole(row)"
              >编辑</el-button
            >
            <el-popconfirm
              :title="`确定删除${row.roleName}吗?`"
              @confirm="deleteRole(row.id)"
            >
              <template #reference>
                <el-button size="small" icon="Delete" type="danger"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="pageSize"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @size-change="getRoleList"
        @current-change="getRoleList"
      />
    </el-card>
    <!-- 添加或更新角色对话框 -->
    <el-dialog
      v-model="roleDialog"
      :title="newRoleData.id ? '编辑角色' : '添加角色'"
      width="30%"
    >
      <el-form>
        <el-form-item label="角色名称:">
          <el-input
            v-model="newRoleData.roleName"
            placeholder="请输入角色名"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitAddRole"
            :disabled="!newRoleData.roleName"
          >
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分配权限抽屉 -->
    <el-drawer v-model="permissionDrawer" title="分配角色权限" direction="rtl">
      <el-tree
        ref="menuListTree"
        :data="menuList"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="menuSelectArr"
        :props="TreeOptions"
      />
      <template #footer>
        <el-button
          type="default"
          size="default"
          @click="permissionDrawer = false"
          >取消</el-button
        >
        <el-button type="primary" size="default" @click="submitMenuList"
          >提交</el-button
        >
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import * as roleRequest from "@/api/acl/role";
import checkResult from "@/utils/notice";
// 引入框架仓库，用于点击重置按钮刷新
import useLayoutSettingStore from "@/store/modules/setting";
let settingStore = useLayoutSettingStore();

let pageNo = ref<number>(1);
let limit = ref<number>(5);
let pageSize = ref<number[]>([5, 10, 20]);
let total = ref<number>(0);
let tableLoading = ref<boolean>(false);

let roleList = ref([]);

//权限菜单相关
let menuList = ref<any>([]);
let menuSelectArr = ref<number[]>([]);
let menuListTree = ref();
let TreeOptions = reactive<any>({
  label: "name",
  children: "children",
});

//收集要添加用户角色的数据
let newRoleData = reactive<any>({
  roleName: "",
});

//角色更新相关
let roleDialog = ref<boolean>(false);

//角色权限相关
let permissionDrawer = ref<boolean>(false);

//搜索相关
let keyword = ref<string>("");
const searchRole = () => {
  getRoleList(1, keyword.value);
};

//获取所有用户角色列表
const getRoleList = async (pager: number = 1, roleName: string = "") => {
  tableLoading.value = true;
  let result: any = await roleRequest.role(pageNo.value, limit.value, roleName);
  if (result.code == 200) {
    total.value = result.data.total;
    roleList.value = result.data.records;
  }
  keyword.value = "";
  tableLoading.value = false;
  pageNo.value = pager;
};

//添加用户角色按钮点击
const addRole = () => {
  // 先清空上一次数据
  Object.assign(
    newRoleData,
    JSON.parse(
      JSON.stringify({
        roleName: "",
      }),
    ),
  );
  delete newRoleData.id;
  roleDialog.value = true;
};

//编辑用户角色
const updateRole = (row: any) => {
  Object.assign(newRoleData, JSON.parse(JSON.stringify(row)));
  roleDialog.value = true;
};

//提交添加或更新用户角色
const submitAddRole = async () => {
  if (newRoleData.id) {
    //有id，更新用户角色
    let result = await roleRequest.update(newRoleData);
    checkResult(result, "更新用户角色", "code", 200);
    //更新则留在当前页
    getRoleList(pageNo.value);
  } else {
    //无id，添加用户角色
    let result = await roleRequest.save(newRoleData);
    checkResult(result, "添加用户角色", "code", 200, getRoleList);
  }
  roleDialog.value = false;
};

//删除用户角色
const deleteRole = async (id: number) => {
  let result = await roleRequest.remove(id);
  checkResult(result, "删除用户角色", "code", 200, getRoleList);
  getRoleList();
};

onMounted(() => {
  getRoleList();
});

//分配角色权限
const setPermission = async (row: any) => {
  Object.assign(newRoleData, JSON.parse(JSON.stringify(row)));
  let result = await roleRequest.toAssign(newRoleData.id);
  if (result.code == 200) {
    menuList.value = result.data;
    menuSelectArr.value = await filterSelectArr(menuList.value);
    permissionDrawer.value = true;
  }
};
// 封装递归方法将角色菜单整理为接口所需格式
const filterSelectArr = async (
  allArr: any,
  needKey: string = "id",
  selectKey: string = "select",
  childrenKey: string = "children",
  initArr: any = [],
) => {
  allArr.forEach((i: any) => {
    if (!i[childrenKey] || i[childrenKey].length <= 0) {
      if (i[selectKey]) {
        initArr.push(i[needKey]);
      }
    } else {
      filterSelectArr(i[childrenKey], needKey, selectKey, childrenKey, initArr);
    }
  });
  return initArr;
};
// 当提交新的角色权限
const submitMenuList = async () => {
  if (newRoleData.id) {
    let permissionIdList = [
      ...menuListTree.value.getCheckedKeys(),
      ...menuListTree.value.getHalfCheckedKeys(),
    ];
    let result = await roleRequest.doAssign(permissionIdList, newRoleData.id);
    checkResult(result, "更新角色权限", "code", 200);
    getRoleList(pageNo.value);
    permissionDrawer.value = false;
    menuSelectArr.value = []; //不清除会导致之前数据残留,或者也可以直接刷新页面
    window.location.reload();
  }
};
</script>

<style scoped lang="scss">
.searchForm {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
